import os
import cgi
from ivic.core import Logging
import ivic_config
import monitor

logger = Logging.get_logger(__name__)

class VMCWebServer:

    def __base_url(self, environ):
        return 'http://' + environ['HTTP_HOST'] + environ['SCRIPT_NAME']

    def __this_url(self, environ):
        return 'http://' + environ['HTTP_HOST'] + environ['SCRIPT_NAME'] + environ['PATH_INFO']

    def notfound(self, environ, start_response):
        status = '404 Not Found'
        response_headers = [('Content-type','text/plain')]
        start_response(status, response_headers)
        path_info = environ['PATH_INFO']
        content = [ "Page %s not found !" % path_info ]
        return content

    def __style(self):
        return '''<style type="text/css">
body {
  font-size: 1em;
  font-family: monospace;
}
h1 {
  text-align: center;
}
div.center {
  width: 600px;
  margin: 0px auto;
}
table {
  width: 600px;
  margin: 0px auto;
  border-width: 1px;
  border-style: solid;
  border-color: gray;
  border-collapse: collapse;
}
th, td {
  border-width: 1px;
  padding: 1px;
  border-style: solid;
  border-color: gray;
}
</style>\n'''

    def pm_info(self, environ, start_response):
        status = '200 OK'
        response_headers = [('Content-type','text/html')]
        start_response(status, response_headers)

        content = []
	cpu_info = monitor.get_cpu_info()
	a = int(float(cpu_info[2])*1000)
	cpu_info[2] = str(a/10) + "." + str(a%10)
	mem_info = monitor.get_mem_info()
	disk_info = monitor.get_disk_info()
	network_info = monitor.get_network_info()
        content.append('''
<html>
<head>
<title>hello</title>
%s
</head>
<body>
<h1>hello</h1>
<table>
<tr><td>CPU Type</td><td>%s</td></tr>
<tr><td>CPU num</td><td>%s</td></tr>
<tr><td>CPU Usage</td><td>%s</td></tr>
<tr><td>mem total(K)</td><td>%s</td></tr>
<tr><td>mem free(K)</td><td>%s</td></tr>
<tr><td>disk device</td><td>%s</td></tr>
<tr><td>disk total(K)</td><td>%s</td></tr>
<tr><td>disk free(K)</td><td>%s</td></tr>
<tr><td>net_ifname</td><td>%s</td></tr>
<tr><td>net_tx(B)</td><td>%s</td></tr>
<tr><td>net_rx(B)</td><td>%s</td></tr>
</table>
</body>
</html>
''' % (self.__style(), cpu_info[0], cpu_info[1], cpu_info[2], mem_info[0], mem_info[1], disk_info[0], disk_info[1], disk_info[2], network_info[0], network_info[1], network_info[2]))

        return content

    def vm_list(self, environ, start_response):
        status = '200 OK'
        response_headers = [('Content-type','text/html')]
        start_response(status, response_headers)

        content = []
	dom_uuids, dom_statuses = monitor.get_domlist_info()
        content.append('''
<html>
<head>
<title>hello</title>
%s
</head>
<body>
<h1>Virtual Machine List</h1>
<table>
<tr><th>vm uuid</th><th>vm state</th><th>details</th></tr>
''' % self.__style())
	for i in xrange(len(dom_uuids)):
		content.append("<tr><td>%s</td><td>%s</td><td><a href='dominfo?uuid=%s'>details</a></td></tr>" % (dom_uuids[i], dom_statuses[i], dom_uuids[i]))
	content.append(
'''</table>
</body>
</html>
''')

        return content

    def vnet_list(self, environ, start_response):
        status = '200 OK'
        response_headers = [('Content-type','text/html')]
        start_response(status, response_headers)

        content = []
	network_uuids, network_statuses, network_vpnservers = monitor.get_networklist_info()
        content.append('''
<html>
<head>
<title>hello</title>
%s
</head>
<body>
<h1>Virtual Network List</h1>
<table>
<tr><th>network_uuid</th><th>vpnserver</th><th>status</th><th>details</th></tr>
''' % self.__style())
	for i in xrange(len(network_uuids)):
		content.append("<tr><td>%s</td><td>%s</td><td>%s</td><td><a href='networkinfo?uuid=%s'>details</a></td></tr>" % (network_uuids[i], network_vpnservers[i], network_statuses[i], network_uuids[i]))
	content.append(
'''</table>
</body>
</html>
''')

        return content

    def dominfo(self, environ, start_response):
        status = '200 OK'
        response_headers = [('Content-type','text/html')]
        start_response(status, response_headers)
	params = cgi.parse_qs(environ['QUERY_STRING'])
        dom_uuid = params['uuid'][0]
	#if not params.has_key('uuid'):
	#	return
        items = ["uuid", "state", "cputime", "memtotal", "memused", "disk_read", "disk_write", "vif_rx", "vif_tx", "vnc_port"]
        dom_status = monitor.get_dom_status(dom_uuid)
        show_dom_info = False
        dom_info = []

        if dom_status != "stopped":
          show_dom_info = True
          dom_info = monitor.get_dom_info(dom_uuid)

        vmxml_root = ivic_config.get_dir("vmxml_root")
        dom_xml_lines = open(vmxml_root + "/" + dom_uuid.strip() + ".xml", "r").read()
	dom_xml_lines = dom_xml_lines.replace("<", "&lt;")
	dom_xml_lines = dom_xml_lines.replace(">", "&gt;")

        content = []
        content.append('''
<html>
<head>
<title>hello</title>
%s
</head>
<body>
<h1>Virtual Machine Information</h1>
<table>
''' % self.__style())
	if show_dom_info:
		for i in xrange(items):
			content.append("<tr><td>%s</td><td>%s</td></tr>" % (items[i], dom_info[i]))
		content.append("</table><table>")
	content.append("<tr><td><pre>%s</pre></td></tr>" % dom_xml_lines)
	content.append(
'''</table>
</body>
</html>
''')

	return content

    def networkinfo(self, environ, start_response):
        status = '200 OK'
        response_headers = [('Content-type','text/html')]
        start_response(status, response_headers)
	params = cgi.parse_qs(environ['QUERY_STRING'])
        network_uuid = params['uuid'][0]
        network_root = ivic_config.get_dir("network_root")
        network_xml_lines = open(network_root + "/" + network_uuid.strip() + ".xml", "r").read()
	network_xml_lines = network_xml_lines.replace("<", "&lt;")
	network_xml_lines = network_xml_lines.replace(">", "&gt;")

        content = []
        content.append('''
<html>
<head>
<title>hello</title>
%s
</head>
<body>
<h1>Virtual Network Information</h1>
<table>
''' % self.__style())
	content.append("<tr><td><pre>%s</pre></td></tr>" % network_xml_lines)
	content.append(
'''</table>
</body>
</html>
''')

        return content

    def index(self, environ, start_response):
        status = '200 OK'
        response_headers = [('Content-type','text/html')]
        start_response(status, response_headers)

        content = []
        content.append('''<html>
<head>
<title>Index Page</title>
%s
</head>
<body>
<h1>Index Page</h1>
<img src="../images/n1.gif"/>
<div class="center">
<ul>
<li><a href="pm_info">Physical Machine information</a></li>
<li><a href="vm_list">Virtual Machines List</a></li>
<li><a href="vnet_list">Virtual Networks List</a></li>
</ul>
</body>
</html>
''' % self.__style())

        return content

    def __redirect(self, target, environ, start_response):
        status = '301 Moved Permanently'
        location = self.__base_url(environ) + target
        response_headers = [
                ('Content-type','text/plain'),
                ('Location',location)
        ]
        start_response(status, response_headers)

        content = ['Requested page moved to: ' + location]
        return content

    def __call__(self, environ, start_response):
        logger.debug('entering wsgi sample')

        try:
            path_info = environ['PATH_INFO']
            if not path_info.startswith('/'):
                content = self.__redirect('/' + path_info, environ, start_response)

            path_info = path_info.strip('/')
            if not path_info:
                path_info = 'index'

            if hasattr(self, path_info):
                content = getattr(self, path_info)(environ, start_response)
            else:
                content = self.notfound(environ, start_response)
        except Exception, e:
            logger.exception(e)

        logger.debug('exiting wsgi sample app')
        return content
